#include "fd_guard.h"
#include <unistd.h>

namespace wilson::sys
{
    fd_guard::fd_guard(int fd) 
        : fdg_fd{ fd }
    {
        if (fd != -1)
            set_nonblk();
    }

    ::std::error_code fd_guard::error() const noexcept
    {
        if (fdg_fd == -1)
        {
            return { errno, ::std::system_category() };
        }
        return {};
    }
    
    fd_guard::~fd_guard() noexcept
    {
        close();
    }

    void fd_guard::close() noexcept
    {
        if (fdg_fd) 
        {
            ::close(fdg_fd);
            fdg_fd = 0;
        }
    }

    fd_guard::fd_guard(fd_guard&& other) noexcept
        : fdg_fd{ other.fdg_fd }
    {
        other.fdg_fd = 0;
    }

    fd_guard& fd_guard::operator=(fd_guard&& other) noexcept
    {
        if (fdg_fd) [[unlikely]]
            close();
        fdg_fd = other.fdg_fd;
        other.fdg_fd = 0;
        return *this;
    }

    fd_guard fd_guard::dup() const noexcept
    {
        return fd_guard{ ::dup(fdg_fd) };
    }
}
